import pyb
import sensor, image, time, math
import os, tf


sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQVGA) # we run out of memory if the resolution is much bigger...
sensor.set_brightness(2000)
sensor.skip_frames(time = 20)
sensor.set_auto_gain(False)  # must turn this off to prevent image washout...
sensor.set_auto_whitebal(False)  # must turn this off to prevent image washout...
clock = time.clock()

net_path = "mobilenet.tflite"                                  # 定义模型的路径
labels = [line.rstrip() for line in open("/sd/lebal_eiq.txt")]   # 加载标签
net = tf.load(net_path, load_to_fb=True)                                  # 加载模型


#识别
def img_model(net):
    img = sensor.snapshot()
    for r in img.find_rects(threshold = 30000):             # 在图像中搜索矩形
        img.draw_rectangle(r.rect(), color = (255,0, 0))   # 绘制矩形外框，便于在IDE上查看识别到的矩形位置
        img1 = img.copy(1,1,r.rect())                           # 拷贝矩形框内的图像
        for obj in tf.classify(net , img1, min_scale=1.0, scale_mul=0.5, x_overlap=0.0, y_overlap=0.0):
           # print("**********\nTop 1 Detections at [x=%d,y=%d,w=%d,h=%d]" % obj.rect())
            sorted_list = sorted(zip(labels, obj.output()), key = lambda x: x[1], reverse = True)
            # 打印准确率最高的结果
            for i in range(1):
                print("%s = %f" % (sorted_list[i][0], sorted_list[i][1]))


while(True):
    img_model(net)
    pass

